#!/usr/bin/env python
# -*- coding:utf-8 -*- #
from django.http import HttpResponse
from django.utils import simplejson
import uuid

def getParam(request,key,default = None):
    return request.POST.get(key,default) or request.GET.get(key,default)

def ext(fname):
    pieces = fname.split('.')
    if len(pieces) < 2:
        return None
    return pieces[-1].lower()

def encode(o):
    if isinstance(o,set) or isinstance(o,list):
        return ''.join(('[',','.join(o),']'))
    elif isinstance(o,dict):
        return ''.join(('{',','.join(map(lambda (x,y):''.join((encode(x),':',encode(y))),o.items())),'}'))
    elif isinstance(o,str):
        return o
    elif isinstance(o,bool):
        return 'true' if o else 'false'
    elif isinstance(o,int) or isinstance(o,long) or isinstance(o,float):
        return str(o)
    return o.__dict__

class JsonResult(object):
    
    def __init__(self):
        self.retcode = 'success'
        self.retdata = {}
        
    def fail(self,retcode):
        self.retcode = retcode
        self.retdata = {}
        return self
        
    def response(self):
        json = {'code':self.retcode,'data':self.retdata}
        return HttpResponse(simplejson.dumps(json,default=encode),mimetype='text/html')
    
def respError(code,msg=None):
    return JsonResult().fail(code).response()

def createSessionId():
    return str(uuid.uuid4())